<?php
namespace app\api\controller;

use think\Request;
use think\Config;
use think\Session;
use think\Loader;
use think\Cookie;
use think\Db;
use app\model\UserModel;
use app\model\CompanyModel;
// use think\Redis;
use app\common\BaseController;
use app\common\Compress;
use redis\Redis;
use app\common\Auth\JwtAuth;
use app\common\Tool\ApiErrDesc;
use think\Log;


class User extends BaseController
{
    private $tables = 'user';
    private $table_view = 'view_user';
    private $table_view_app = 'view_new_app_meeting_info';
    private $table_view_app_copy = 'view_new_app_meeting_info_copy';
    private $table_view_member= 'view_commodity_orders';
    protected $redis = null;
    
    public function _initialize(){
        $this->request = Request::instance();
        $this->noNeedLogin = ['session_set','upload_post'];
        $this->redis = new Redis();
    }   
    /**
     * 测试用户接口
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-09-21T09:34:16+0800
     * @LastTime     2020-09-21T09:34:16+0800
     */
    public function Testadd(){
        $uid  = $this->request->param('id')?:$this->uid;
        $openid = $this->request->param('openid');

        $where = 'id = '.$uid;
        $data = [

        ];
        $res = $this->update('user', $where, $data);


       return toJson(['message'=>'手机号码不能为空','code'=>200,'data'=>$data]);
    }
    /**
     * 发送短信验证码
     * @param mobile 手机号
     *        type   
     *                ht-后台-请求验证码
     */
    public function send_get(){

        $mobile = $this->request->param('mobile');
        $type  = $this->request->param('type');

        if( empty($mobile)){
            return toJson(['message'=>'手机号码不能为空','code'=>400]);
        }

        Loader::import('Sms_YunPian', EXTEND_PATH);
        $sms = new \Sms_YunPian();
        $code = mt_rand(100000,999999);
            //    $this->redis::set('phonecode_'.$this->uid,$code,180);
            // $this->redis::set('phonecode_'.$this->uid.'_mobile',$mobile,180);
            // var_dump($code);
            // exit();
        if($sms->send($mobile,$code)){
            //设置cookie
            // Cookie::set('Cookie_Message_'.$this->uid ,$code,1200);
            $this->redis::set('phonecode_'.$this->uid,$code,180);
            $this->redis::set('phonecode_'.$this->uid.'_mobile',$mobile,180);

            /**测试code**/
            //$this->redis::set('phonecode_'.$this->uid,'123456');
            
            //返回结果        
            return toJson(['message'=>'发送短信验证成功','code'=>200]);
        }else{
            return toJson(['message'=>'发送短信验证失败','code'=>400]);
        }
    }


    /**
     * 验证短信验证码
     * @param code 验证码
     * @param code 验证码
     * @param code 验证码
     * @param type chphone --更换手机号  --testu测试用户
     * lasttime - 去除前端密码-后台设置密码(短信登录)
     */
    public function binding_post(){
        $sharecode = $this->request->param('sharecode');
        //$this->redis::set('phonecode_'.$this->uid,'123456',1200);
        $mobile = $this->request->param('mobile');
        $password = trim($this->request->param('password'));
        $password_confirm = trim($this->request->param('password_confirm'));
        $message_code = $this->request->param('message_code');
        $type = $this->request->param('type');/*更换手机号  chphone  testu*/

        if($type == 'chphone'){

            if( empty($mobile) ){
                return toJson(['message'=>'手机号不能为空','code'=>400]);
            }
            if( empty($message_code)){
                return toJson(['message'=>'验证码不能为空','code'=>400]);
            }
            // $verify_code = Cookie::get('Cookie_Message_'.$this->uid);
            $verify_code = $this->redis::get('phonecode_'.$this->uid);


            $check_send_mobile = $this->redis::get('phonecode_'.$this->uid.'_mobile');

            if($mobile != $check_send_mobile){
                return toJson(['message'=>'手机号错误','code'=>400]);
            }

            if( $verify_code !== $message_code ){
                return toJson(['message'=>'验证码不正确','code'=>400]);
            }

            $userData = UserModel::where('id','eq',$this->uid)->where('deleteTime is null')->find();

            if(!empty($userData->mobile)){
                return toJson(['message'=>'账户已绑定','code'=>200]);
            }
            $userData->mobile = $mobile;
            $result = $userData->save();
            if($result === false){
                return toJson(['message'=>'数据出错，请联系客服！','code'=>400]);
             }
    
            return toJson(['message'=>'绑定成功','code'=>200]);


        }
        /**分割线**/
        
        if( empty($mobile) ){
            return toJson(['message'=>'手机号不能为空','code'=>400]);
        }

        // if( empty($password) || empty($password_confirm)){
        //     return toJson(['message'=>'密码不能为空','code'=>400]);
        // }

        // if( $password !== $password_confirm ){
        //     return toJson(['message'=>'两次密码不一致请重新输入','code'=>400]);
        // }

        if( empty($message_code)){
            return toJson(['message'=>'验证码不能为空','code'=>400]);
        }

        // $verify_code = Cookie::get('Cookie_Message_'.$this->uid);
        $verify_code = $this->redis::get('phonecode_'.$this->uid);


        $check_send_mobile = $this->redis::get('phonecode_'.$this->uid.'_mobile');

        if($mobile != $check_send_mobile){
            return toJson(['message'=>'手机号错误','code'=>400]);
        }

        if( $verify_code !== $message_code ){
            return toJson(['message'=>'验证码不正确','code'=>400]);
        }

        $mobileData = UserModel::where('mobile','eq',$mobile)->where('deleteTime is null')->find();
        if($mobileData){
            return toJson(['message'=>'手机号已绑定','code'=>400]);
        }
        /**是否发送验证码手机号**/

        $userData = UserModel::where('id','eq',$this->uid)->where('deleteTime is null')->find();
        if(!empty($userData->mobile)){
            return toJson(['message'=>'账户已绑定','code'=>400]);
        }


        
        $userData->mobile = $mobile;        
        //$userData->password = md5($password.Config::get('salt'));

        if($type=='testu'){
            $userData->name = 'ZSICP测试用户'.$this->uid;
            $userData->imgurl = 'user/userlogo.png';
            $userData->identitycard = '442000'.date('Ymd'.time()).'11'.$this->uid;
            $userData->address = '广东省中山市协成信息科技有限公司';
            $userData->is_person_verify = 1;
            $userData->nickname = 'ZSICP测试用户'.$this->uid;
            $userData->city = 'ZS';


            /**同步数据到后台**/
            $dbconf = Config::get('vister_db');
                $where = 'username = "'.'ZSICP测试用户'.$this->uid.'" and openid = "'.$this->user->openid.'" and is_deleted = 0';
                //可用opendid代替
                $res = Db::connect($dbconf)->table('view_system_user')->where($where)->find();
                if($res!=NULL){
                    $updata = [
                        'username'=>'ZSICP测试用户'.$this->uid,
                        'openid' => $this->user->openid,
                        'phone' => $userData->mobile,
                        //'password' => $userData->password,
                        'desc' => "同步用户,来自移动端注册更新数据",
                    ];
                    Db::connect($dbconf)->table('system_user')->where($where)->data($updata)->update();
                }else{
                    //$u_info = $this->find('view_user','openid = "'.$this->user->openid.'"');
                    $indata = [
                        'openid' => $this->user->openid,
                        'username' => 'ZSICP测试用户'.$this->uid,
                        //'password' => $userData->password,
                        'phone' => $userData->mobile,
                        'desc' => "同步用户,来自移动端注册",
                        'status' => 1,
                        'create_at' => date("Y-m-d H:i:s",time())
                    ];
                    Db::connect($dbconf)->table('system_user')->insert($indata);  
                }

        }
        //end testu
                      
        $result = $userData->save();
        if($result === false){
            return toJson(['message'=>'数据出错，请联系客服！','code'=>400]);
        }
        //同步数据库   
        if($type!="testu" && $type!="chphone"){
            $dbconf = Config::get('vister_db');
            $where = 'openid = "'.$this->user->openid.'"';
            //可用opendid代替
            $res = Db::connect($dbconf)->table('view_system_user')->where($where)->find();
            if($res!=NULL){
                $updata = [
                    // 'username'=>'ZSICP测试用户'.$this->uid,
                    'openid' => $this->user->openid,
                    'phone' => $userData->mobile,
                    //'password' => $userData->password,
                    'desc' => "同步用户,来自移动端注册更新数据",
                    'authorize' => 9,
                    // 'role' => 0,
                ];
                Db::connect($dbconf)->table('system_user')->where($where)->data($updata)->update();
            }else{
                //$u_info = $this->find('view_user','openid = "'.$this->user->openid.'"');
                $indata = [
                    'openid' => $this->user->openid,
                    // 'username' => 'ZSICP测试用户'.$this->uid,
                    //'password' => $userData->password,
                    'phone' => $userData->mobile,
                    'desc' => "同步用户,来自移动端注册",
                    'status' => 1,
                    'create_at' => date("Y-m-d H:i:s",time()),
                    'authorize' => 9,
                ];
                Db::connect($dbconf)->table('system_user')->insert($indata);  
            }
        }
        //创建默认会员
        $res = $this->make_member($this->user->openid,0,'2100-12-30');
        //分享添加积分
        if($sharecode){
            $share_user = $this->find('view_user','openid like "%'.$sharecode.'"');
            try{
                $this->member_integral($share_user['openid'],5,'add');
            }catch(\Throwable $th){

            }
        }
        return toJson(['message'=>'绑定成功','code'=>200,'data'=>$userData]);
    }

    public function session_set(){
        // $redis = new Redis();
        // var_dump($redis::get('dev_hour_appointment_issend'));
        // exit();
        // 保留测试

        $jwtAuth = $this->jwtAuth;

        $token = $jwtAuth->setUid($this->request->param('openid'))->encode()->getToken(); //包裝uid 跟用戶權限

        return $this->jsonSuccessData($token);
        var_dump($token);
        exit();
        $token = makeToken();
        Session::set('Session_User_'.$token, 'ox8satx3ZP6jQtdbz1JRItqI16U8');
        $ismobile = 0;
        return toJson(['token'=>$token,'subscribe'=>1,'ismoblie'=>$ismobile]);
    }
    public static function str_n_pos($str,$find,$n){
            
            $pos_val = 0;
            for ($i=1;$i<=$n;$i++){
    
                $pos = strpos($str,$find);
    
                $str = substr($str,$pos+1);
    
                $pos_val=$pos+$pos_val+1;
    
            }
    
    $count = $pos_val-1;
    
            return $count;
    
        }

    //上传身份证验证
    public function upload_post(){
        $image_type = $this->request->param('c_type')?:'front';//back front
        $file = $this->request->file('imgurl');
        $type = $this->request->param('type'); /*修改信息身份证-----chidcard*/
        $scan = $this->request->param('uptype'); /* file url*/
        $url =  $this->request->param('url'); 

        // if($scan=='url'){
        //     Loader::import('Baidu_AI', EXTEND_PATH);
        //     $ai = new \Baidu_AI();
        //     $res = $ai->identitycard_verify($url,$image_type);
        //     return toJson(['data'=>$res]);
            
        // }else{
            $info = $file->validate(['ext'=>'jpg,jpeg,png'])
                     ->move(Config::get('upload_identitycard_path'));
        // }

        if($info){
            // var_dump($info->getSize());
            Loader::import('Baidu_AI', EXTEND_PATH);
            $ai = new \Baidu_AI();
            //200kb  == 190000
            if($info->getSize() > 700000){

                $source = Config::get('upload_identitycard_path') . $info->getSaveName();
                $path = Config::get('upload_identitycard_thumb_path').'/'.date('Ymd');
                if(!file_exists($path)){
                    mkdir($path,0777,true);
                }
                $image_name = md5(time().$source);
                $dst_img = $path.'/'.$image_name.'.jpg';
                $percent = 0.98;  #原图压缩，不缩放，但体积大大降低 不要太小会糊
                $image = (new Compress($source,$percent))->compressImg($dst_img);
                $res = $ai->identitycard_verify($dst_img,$image_type);
                $true_path = str_replace('/www/wwwroot/dev-visiter.com//','http://devs.zsicp.com/',$dst_img);

            }else{
                $res = $ai->identitycard_verify(Config::get('upload_identitycard_path') . $info->getSaveName(),$image_type);
                $true_path = str_replace('/www/wwwroot/dev-visiter.com//','http://devs.zsicp.com/',Config::get('upload_identitycard_path') .$info->getSaveName());
            }   

            try{
                if($image_type=='front'){
                    $name = $res['words_result']['姓名']['words'];
                    $sex = $res['words_result']['性别']['words'];
                    $address = $res['words_result']['住址']['words'];
                    $identitycard = $res['words_result']['公民身份号码']['words'];
                    $birth = $res['words_result']['出生']['words'];
                    /*民族*/
                    $mz = $res['words_result']['民族']['words'];
                    $data = ['name'=>$name,'sex'=>$sex,'address'=>$address,'identitycard'=>$identitycard,'birthday'=>$birth];
                }
          
                if($image_type=='back'){
                    $get_date = $res['words_result']['签发日期']['words'];
                    $lost_date = $res['words_result']['失效日期']['words'];
                    $ca = $res['words_result']['签发机关']['words'];
                    $data = ['type'=>'back','get_date'=>$get_date,'lost_date'=>$lost_date,'ca'=>$ca];
                    if($data['get_date']=="" || $data['lost_date']==""){return toJson(['message'=>'请上传正确的身份证','code'=>'400']);}

                    if($data['lost_date']=='长期'){
                        $data['idcard_date_type']=2;
                    }else{
                        $data['idcard_date_type']=1;
                    }

                }
            }catch(\Throwable $th){
                return toJson(['message'=>'请上传正确的身份证','code'=>'400']);
            }
                /*此处修改身份证信息 更新*/
                if($type == 'chidcard'){
                    #code ......
                     #
                }

                return toJson(['message'=>'身份证验证成功','code'=>'200','data'=>$data,'src'=>$true_path]);

        }else{
            // 返回失败获取错误信息
            return toJson(['message'=>$file->getError(),'code'=>'400']);
        }
    }

    //保存用户身份信息
    public function information_post(){
        $type = $this->request->param('type');//save | edit
        $name = $this->request->param('name');
        $sex = $this->request->param('sex');
        $address = $this->request->param('address');
        $identitycard = $this->request->param('identitycard');
        $imgurl = $this->request->param('imgurl');

        if( empty($name) || $sex==NULL || empty($address) || empty($identitycard) || empty($imgurl) ){
            return toJson(['message'=>'参数不全，请检查','code'=>'400']);
        }
        if($type=='save' || $type!='edit'){
        $idcardData = UserModel::where('identitycard','eq',$identitycard)->where('deleteTime is null')->find();
        if($idcardData){
            return toJson(['message'=>'身份证号码已注册','code'=>'400']);
        }
        }


        $userData = UserModel::where('id','eq',$this->uid)->where('deleteTime is null')->find();
        if(empty($userData)){
            return toJson(['message'=>'账户不存在','code'=>'400']);
        }

        $userData->name = $name;
        $userData->sex = $sex;
        $userData->address = $address;
        $userData->identitycard = $identitycard;
        $userData->imgurl = $imgurl;        
        $result = $userData->save();

        if($result === false){
            return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
        }

        return toJson(['message'=>'保存成功','code'=>200]);
    }
    /**人脸对比**/
    public function verify_post(){
        $userData = UserModel::where('id','eq',$this->uid)->where('deleteTime is null')->find();
        if(empty($userData)){
            return toJson(['message'=>'账户不存在','code'=>'400']);
        }

        $name = $this->request->param('name')?:false;
        $address =$this->request->param('address')?:false;
        $sex = $this->request->param('sex')?:false;
        $identitycard =$this->request->param('identitycard')?:false;
        $imgurl = $this->request->param('src')?:false;
        $sharecode = $this->request->param('sharecode');
        $birth =  $this->request->param('birth');
        if(!$birth || $birth =="undefined"){
            $birth = substr($identitycard,6,4)."-".substr($identitycard,10,2)."-".substr($identitycard,12,2);
        }
        //身份证反面
        $imgurl_b = $this->request->param('imgurl_b')?:false;
        $idcard_date_type = $this->request->param('idcard_date_type')?:false;
        $idcard_date_begin = $this->request->param('idcard_date_begin')?:NULL;
        $idcard_date_end = $this->request->param('idcard_date_end')?:NULL;

        $userData->name = $name;
        $userData->sex = $sex;
        $userData->address = $address;
        $userData->identitycard = $identitycard;
        $userData->birthday = $birth;
        //匹配出生日期 暂无
        
        $userData->imgurl = $imgurl; 
        //身份证反面
        $userData->imgurl_b = $imgurl_b;
        if($idcard_date_type=='1'){
            $userData->idcard_date_begin = $idcard_date_begin;
            $userData->idcard_date_end = $idcard_date_end; 
        }
        $userData->idcard_date_type = (int)$idcard_date_type;

        //$result = $userData->save();
        
        $file = $this->request->file('imgurl');
        $info = $file->validate(['ext'=>'jpg,jpeg,png'])
                     ->move(Config::get('upload_person_path'));
        if($info){
            Loader::import('Baidu_AI', EXTEND_PATH);
            $ai = new \Baidu_AI();
            if($info->getSize() > 700000){
                $source = Config::get('upload_person_path') . $info->getSaveName();
                $path = Config::get('upload_person_thumb_path').'/'.date('Ymd');
                if(!file_exists($path)){
                    mkdir($path,0777,true);
                }
                $image_name = md5(time().$source);
                $dst_img = $path.'/'.$image_name.'.jpg';
                $percent = 0.98;  #原图压缩，不缩放，但体积大大降低
                $image = (new Compress($source,$percent))->compressImg($dst_img);
                $res = $ai->person_verify($dst_img,$userData->identitycard,$userData->name);
                $true_path = str_replace('/www/wwwroot/dev-visiter.com//','http://devs.zsicp.com/',$dst_img);
            }else{

                $res = $ai->person_verify(Config::get('upload_person_path') . $info->getSaveName(),$userData->identitycard,$userData->name);
                $true_path = str_replace('/www/wwwroot/dev-visiter.com//','http://devs.zsicp.com/',Config::get('upload_person_path').$info->getSaveName());

            }

            if($res['error_code'] == '222361' ){
                return toJson(['message'=>'服务连接失败，请重新上传','code'=>400]);
            }

            if($res['error_code'] == '222350' ){
                return toJson(['message'=>'照片不存在或质量过低，请重新上传','code'=>400]);
            }

            if($res['error_code'] == '222351' ){
                return toJson(['message'=>'身份证号与姓名不匹配或该身份证号不存在','code'=>400]);
            }

            if($res['error_code'] == '222352' ){
                return toJson(['message'=>'身份证名字格式错误','code'=>400]);
            }

            if($res['error_code'] == '222353' || $res['error_code'] == '222022'){
                return toJson(['message'=>'身份证号码格式错误','code'=>400]);
            }

            if($res['error_code'] == '222354' ){
                return toJson(['message'=>'不存在此身份证号','code'=>400]);
            }

            if($res['error_code'] == '222355' ){
                return toJson(['message'=>'没有对应的照片','code'=>400]);
            }

            if($res['error_code'] == '222360' ){
                return toJson(['message'=>'身份证号码或名字校验不通过','code'=>400]);
            }

            if($res['error_code'] == 0 && $res['result']['score'] >= 90 ){    
                $userData->is_person_verify = 1;
                $userData->personimg =  $true_path;
                $result = $userData->save();

                if($result === false){
                    return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
                }

                /**/

                $dbconf = Config::get('vister_db');
                $where = 'username = "'.$this->user->name.'" and openid = "'.$this->user->openid.'" and is_deleted = 0'; //可用opendid代替
                $res = Db::connect($dbconf)->table('system_user')->where($where)->find();
                if($res!=NULL){
                    $updata = [
                        'username'=>$this->user->name?:$name,
                        'openid' => $this->user->openid,
                        'phone' => $this->user->mobile,
                        'password' => $this->user->password,
                        'desc' => "同步用户,来自移动端注册更新数据",

                    ];
                    Db::connect($dbconf)->table('system_user')->where($where)->data($updata)->update();
                }else{
                    //$u_info = $this->find('view_user','openid = "'.$this->user->openid.'"');
                    $indata = [
                        'openid' => $this->user->openid,
                        'username' => $this->user->name?:$name,
                        'password' => $this->user->password,
                        'phone' => $this->user->mobile,
                        'desc' => "同步用户,来自移动端注册",
                        'status' => 1,
                        'create_at' => date("Y-m-d H:i:s",time())
                    ];
                    Db::connect($dbconf)->table('system_user')->insert($indata);  
                }
                //添加积分
                $res = $this->member_integral($this->user->openid,10,'add');
                /**
                 * 被分享+积分
                 * 待定其他业务 积分
                 * 如: 单位A分享 注册访客后 单位A添加积分
                 * 丢到bind post了
                 */
                // if($sharecode){
                //     $share_user = $this->find('view_user','openid like "%'.$sharecode.'"');
                //     try{
                //         $this->member_integral($share_user['openid'],5,'add');
                //     }catch(\Throwable $th){

                //     }
                // }

                return toJson(['message'=>'用户验证成功','code'=>'200']);
            }else{
                return toJson(['message'=>'身份证与本人不一致，请重新核对','code'=>'400']);
            }
        }else{
            // 返回失败获取错误信息
            return toJson(['message'=>$file->getError(),'code'=>'400']);
        }
    }
    /**
     * @HtttpRequest                          get|
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-07-06T13:55:54+0800
     * @LastTime     2020-07-06T13:55:54+0800
     * @return       [type]
     */
    public function info_get(){
        $uid = $this->request->param('uid');
        $uid = empty($uid) ? $this->uid : $uid;


        // $userData = UserModel::alias('u')
        //                         ->field('u.*,c.name as cname')
        //                         ->join('company c','u.companyid=c.id','left')
        //                         ->where('u.id','eq',$uid)
        //                         ->find();
       $userData = Db::table('view_user')->where('id = '.$uid)->where('deleteTime is null')->find();

        if(empty($userData)){
            return toJson(['message'=>'用户不存在','code'=>400]);
        }
        if($this->user->roleid != 0){
            $where = 'createuid = '.$this->uid;
            $check_company = $this->find('view_company',$where);
        }else{
            $check_company = NULL;
        }


        
        $ismobile = empty($userData['mobile']) ? 0 : 1;
        $isIdentitycard = empty($userData['identitycard']) ? 0 : 1;  
        $isPersonVerify = $userData['is_person_verify'];
        $memberinfo = $this->vipinfo($uid);
        $u_code = $this->makeOrdersn(ApiErrDesc::Out_Trade_No[1][3]);
        $this->redis::set('code_'.$u_code,$userData['openid'],300);
        $code = $this->user->openid;
        $code=substr($code,-6);

        $link = 'http://devs.zsicp.com/h5?s='.$code;
        $userData['sharecode'] = $code;
        $userData['sharelink'] = $link;
        $redata = [
            'message'=>'获取用户信息成功',
            'code'=>'200',
            'data'=>$userData,
            'ismoblie'=>$ismobile,
            'member'=>$memberinfo,
            'isIdentitycard'=>$isIdentitycard,
            'isPersonVerify'=>$isPersonVerify,
            'u_sn' => $u_code,
        ];
        if($check_company!=NULL){
            $redata['company_status'] = $check_company['status']; 
        }
        return toJson($redata);
    }
    
       /**
        * 邀请列表
        * @HtttpRequest                          get|post
        * @Author       GNLEON
        * @Param
        * @DateTime     2020-09-11T14:31:45+0800
        * @LastTime     2020-09-11T14:31:45+0800
        * @return       [type]                   [description]
        */
		public function getlist(){
	    $page = trim($this->request->param('page'));
	    $pagesize = trim($this->request->param('pagesize'));
	    $keyword = trim($this->request->param('keyword'));
        $type = trim($this->request->param('status'));// 0 1 
        // var_dump($this->user['roleid']);
        // exit();
        // if($this->user['roleid'])

	    $page = empty($page) ? 1 : $page;
	    $pagesize = empty($pagesize) ? 10 : $pagesize;
	    // $where = $keyword ? ":name like %".$keyword."%" : '1=1';
        if($type == '2'){
            $where = 'status = 0';
        }elseif ($type == '3') {
            # code...
            $where = 'status = 1';
        }else{
            $where = ''; 
        }
        
        if($where){
            $where = $where.' and type = 1';
        }else{
            $where = 'type = 1';
        }
        //测试用
        // $this->uid = 1;
        // $this->roleid = 2;
        
        switch ($this->user['roleid']) {
            case 1:
                $deptList =  Db::table('view_new_app_meeting_info_copy')->where($where)->order('createtime desc')->select();
                break;
            // case 2:
            //     $deptList =  Db::table('view_new_app_meeting_info_copy')->where('companyid = '.$this->user['companyid'])->where($where)->order('createtime desc')->select();
            //     break;
            // case 3:
            //     $deptList =  Db::table('view_new_app_meeting_info_copy')->where('deptid = '.$this->user['deptid'])->where($where)->order('createtime desc')->select();
            //     break;
            // case 5:
            // case 6:
            //     $deptList =  Db::table('view_new_app_meeting_info')->where('companyid = '.$this->user['companyid'].' and arrive_status != 0')->select();
            //     break;
            default:
                $deptList =  Db::table('view_new_app_meeting_info_copy')->where('app_uid = '.$this->uid.' and companyid = '.$this->user->companyid)->where($where)->order('createtime desc')->select();
                break;
        }

	    return toJson(['message'=>'获取邀请列表成功','code'=>'200','data'=>$deptList]);
	
	
	}
	
	//访客详情
	 public function infovisit_get(){
        $uid = $this->request->param('uid');
        // $id = $this->request->
        $uid = empty($uid) ? $this->uid : $uid;

       $userData = Db::table('view_user')->where('id = '.$uid)->find();

        if(empty($userData)){
            return toJson(['message'=>'用户不存在','code'=>400]);
        }

        $ismobile = empty($userData['mobile']) ? 0 : 1;
        $isIdentitycard = empty($userData['identitycard']) ? 0 : 1;  
        // $isPersonVerify = $userData['is_person_verify'];

        return toJson(['message'=>'获取访客信息成功','code'=>'200','data'=>$userData,'ismoblie'=>$ismobile,'isIdentitycard'=>$isIdentitycard]);
    }
	
    /**公司内部人员  --- 部门内部人员
     * [Internal_staff description]
     * @HtttpRequest                          get|
     * @Author       GNLEON
     * @Param    req_conpid-公司  req_depid-部门 
     *           keyword -搜索人名 手机
     * @DateTime     2020-07-14T09:47:57+0800
     * @LastTime     2020-07-14T09:47:57+0800
     */
    public function Internal_staff(){
        $type = trim($this->request->param('conType')); //con-公司内部人员  dep-部门内部人员
        $keyword = trim($this->request->param('keyword'));
        $offset = trim($this->request->param('offset'));
        $length = trim($this->request->param('length'));

        $conpid = $this->user['companyid']?:'';
        $depid = $this->user['deptid']?:'';
        if(trim($this->request->param('req_conpid'))){
            $req_conpid = trim($this->request->param('req_conpid'))?:'';
            $search[0] = $req_conpid!=''?'companyid = '.$req_conpid:'';
            // if($req_conpid!=0){$search[0] = 'companyid = '.$req_conpid;}
        }else{
            $req_depid = trim($this->request->param('req_depid'))?:'';
            // if($req_depid!=0){$search[1] = 'companyid = '.$conpid.' and deptid = '.$req_depid;}
            $search[0] = $req_depid!='' ? 'companyid = '.$conpid.' and deptid = '.$req_depid : ''; 
        }
        switch ($type) {
            case 'con':
                if($conpid == 0){return tojson(['code'=>400,'message'=>'您不是该公司员工']);}
                $search[1] = $type?'companyid = '.$conpid:'';

                break;
            case 'dep':
                if($conpid == 0 && $deptid == 0){return tojson(['code'=>400,'message'=>'您不是该公司员工或部门人员']);}
                $search[1] = $type?'companyid = '.$conpid.' and deptid = '.$depid:'';

            default:;
                break;
                $search[1] = '';
                # code...
                break;
        }
         $search[2] = $keyword?' mobile like "%'.$keyword.'%"':'';
         $where =  '';
        foreach ($search as $key => $value) {
            # code...
            if($value){
                $where=$where.$value.' and ';
            }
        }

        $where=substr($where,0,strlen($where)-5);
        $order = 'id desc';

        $data = $this->selectView($this->table_view,$where,'*',$offset,$length,$order);   
        $total = $this->total($this->table_view,$where);
        return tojson(['code'=>200,'data'=>$data,'count'=>$total]);


    }
    /**
     * [getUserList description] 获取用户列表
     * @HtttpRequest                          get|
     * @Author       GNLEON
     * @Param
     * keyword - 手机号  人名
       offset  - 条记录
       length  - 条数
     * @DateTime     2020-07-15T10:54:05+0800
     * @LastTime     2020-07-15T10:54:05+0800
     * @return       [type]                   [description]
     */
    public function get_UserList(){
        $keyword = trim($this->request->param('keyword'));
        $offset = trim($this->request->param('offset'));
        $length = trim($this->request->param('length'));
        $deptid = trim($this->request->param('deptid'));

        // if($deptid){
        //     $where3 = 'deptid = '.$deptid;
        //     $where1 =  'mobile like "%'.$keyword.'%"'.$where3;
        //     $where2 = 'name like "%'.$keyword.'%"'.$where3;
        //     $order = 'id desc';
    
        //     $data_mobile = $this->selectView($this->table_view,$where1,'*',$offset,$length,$order);   
        //     $total_moblie = $this->total($this->table_view,$where1);
    
        //     $data_name = $this->selectView($this->table_view,$where2,'*',$offset,$length,$order);   
        //     $total_name = $this->total($this->table_view,$where2);
    
        //     $data = [
        //         'likepeople' => $data_name,
        //         'likemobile' => $data_mobile,
    
        //     ];
        //     $data_mobile = $this->selectView($this->table_view,$where1,'*',$offset,$length,$order);   
        //     $total_moblie = $this->total($this->table_view,$where1);

        //     return tojson(['code'=>200,'data'=>$data,'mobile_count'=>$total_moblie,'people_count'=>$total_name]);
        // }

        // $ismobile = $this->isMobile($keyword);
        // if($ismobile){
        //      $where =  "mobile like %".$keyword."%";
        // }else{
        //     $where = "name like %".$keyword."%";

        // }
        // 
        
        try {
            $where ='companyid = '.$this->user->companyid.' and vister_uid is not null';
            $get_All_comuserlist = $this->selectView('view_new_app_meeting_info_copy', $where,'vister_uid');
        } catch (\Throwable $th) {
            exception(ApiErrDesc::ERR_PARAMS[1],ApiErrDesc::ERR_PARAMS[0]);
        }

        $all_uid_arr = [];
        foreach ($get_All_comuserlist as $key => $value) {
            # code...
            array_push($all_uid_arr,$value['vister_uid']);           
        }
        
        $all_uid = implode(",", $all_uid_arr);
        $where3 = $all_uid!=''?' and companyid = '.$this->user->companyid.' and id in ('.$all_uid.')':' and companyid = '.$this->user->companyid;
        $where1 =  'mobile like "%'.$keyword.'%"'.$where3;
        $where2 = 'name like "%'.$keyword.'%"'.$where3;
        $order = 'id desc';

        $data_mobile = $this->selectView($this->table_view,$where1,'*',$offset,$length,$order);   
        $total_moblie = $this->total($this->table_view,$where1);

        $data_name = $this->selectView($this->table_view,$where2,'*',$offset,$length,$order);   
        $total_name = $this->total($this->table_view,$where2);

        $data = [
            'likepeople' => $data_name,
            'likemobile' => $data_mobile,

        ];

        return tojson(['code'=>200,'data'=>$data,'mobile_count'=>$total_moblie,'people_count'=>$total_name]);

    }
    
    /*首页数据*/
    public function index(){

		$visittime = $this->request->param('visittime');
        $roleid = $this->user->roleid;
         //今日
        $daybegin = strtotime(date('Y-m-d', time()));
        $dayend = $daybegin+24*60*60;
        $where_nowday = 'app_visittime between "'.$daybegin.'" and "'.$dayend.'"';
        switch ($roleid) {
            case 1:
                $where_select = 'auditing = 0 and type = 2';
                # code...
                break;
            case 2:
            case 8:
                //未访问
                 $where_no_arrive = 'companyid = '.$this->user->companyid.' and status = 0 and arrive_status = 0 and '.$where_nowday;
                //已离开
                 $where_is_arrive = 'companyid = '.$this->user->companyid.' and status = 1 and  arrive_status in (4,5) and '.$where_nowday;
                //待审核
                 $where_auditing_1 = 'companyid = '.$this->user->companyid.' and type = 1 and status = 0 and  auditing = 0 and '.$where_nowday;
                 $where_auditing_2 = 'companyid = '.$this->user->companyid.' and type = 2 and status = 0 and  auditing = 0 and '.$where_nowday;
                break;
            case 5:
            case 6:
                //未访问
                 $where_no_arrive = 'companyid = '.$this->user->companyid.' and status = 0 and arrive_status = 0 and app_uid = '.$this->uid.' and '.$where_nowday;
                //已离开
                 $where_is_arrive = 'companyid = '.$this->user->companyid.' and status = 1 and  arrive_status in (4,5) and app_uid = '.$this->uid.' and '.$where_nowday;
                //待审核
                 $where_auditing_1 = 'companyid = '.$this->user->companyid.' and type = 1 and status = 0 and  auditing = 0 and app_uid = '.$this->uid.' and '.$where_nowday;
                 $where_auditing_2 = 'companyid = '.$this->user->companyid.' and type = 2 and status = 0 and  auditing = 0 and vister_uid = '.$this->uid.' and '.$where_nowday;
                break;
            case 3:
                //未访问
                $where_no_arrive = 'companyid = '.$this->user->companyid.' and deptid = '.$this->user->deptid.' and status = 0 and arrive_status = 0 and '.$where_nowday;
                //已离开
                $where_is_arrive = 'companyid = '.$this->user->companyid.' and deptid = '.$this->user->deptid.' and status = 1 and  arrive_status in (4,5) and '.$where_nowday;
                //待审核
                $where_auditing_1 = 'companyid = '.$this->user->companyid.' and deptid = '.$this->user->deptid.' and type = 1 and status = 0 and  auditing = 0 and '.$where_nowday;
                $where_auditing_2 = 'companyid = '.$this->user->companyid.' and deptid = '.$this->user->deptid.' and type = 2 and status = 0 and  auditing = 0 and vister_uid = '.$this->uid.' and '.$where_nowday;
                //$where_select = 'companyid = '.$this->user->companyid.' and deptid = '.$this->user->deptid.' and auditing = 0 and type = 2';
                break;
            case 4:
                //未访问
                 $where_no_arrive = 'companyid = '.$this->user->companyid.' and status = 0 and arrive_status = 0 and app_uid = '.$this->uid.' and '.$where_nowday;
                //已离开
                 $where_is_arrive = 'companyid = '.$this->user->companyid.' and status = 1 and  arrive_status in (4,5) and app_uid = '.$this->uid.' and '.$where_nowday;
                //待审核
                 $where_auditing_1 = 'companyid = '.$this->user->companyid.' and type = 1 and status = 0 and  auditing = 0 and app_uid = '.$this->uid.' and '.$where_nowday;
                 $where_auditing_2 = 'companyid = '.$this->user->companyid.'type = 2 and status = 0 and  auditing = 0 and vister_uid = '.$this->uid.' and '.$where_nowday;
                //$where_select = 'companyid = '.$this->user->companyid.' and deptid = '.$this->user->deptid.' and auditing = 0 and type = 2 and app_uid = '.$this->uid;
                break;
            default:

                return toJson(['message'=>'获取首页数据成功','code'=>'200','arrive'=>0,'no_arrive'=>0,'auditing'=>0,'data'=>[],'data_arrive'=> [],'data_noarrive'=>[],'data_auditing'=>[]]);
                //$where = 'auditing = 0 and type = 2 and vister_uid = '.$this->uid;
                //return toJson(['message'=>'无权限请求','code'=>'400','data'=>[]]);
                # code...
                break;
        }
        //未访问
        //$where = 'status = 0 and arrive_status = 0 and app_uid = '.$this->uid.' and '.$where_nowday;
        $no_arrive = $this->totalView($this->table_view_app_copy, $where_no_arrive, $field = '*');
        
        //已离开
        //$where = 'status = 1 and  arrive_status in (4,5) and app_uid = '.$this->uid.' and '.$where_nowday;
        $is_arrive_leave = $this->totalView($this->table_view_app_copy, $where_is_arrive, $field = '*');
        
        //待审核 
        //$where = 'type = 1 and status = 0 and  auditing = 0 and app_uid = '.$this->uid.' and '.$where_nowday;
        $is_auditing_app = $this->totalView($this->table_view_app_copy, $where_auditing_1, $field = '*');
        //$where = 'type = 2 and status = 0 and  auditing = 0 and vister_uid = '.$this->uid.' and '.$where_nowday;
        $is_auditing_yy = $this->totalView($this->table_view_app_copy, $where_auditing_2, $field = '*');
        $is_auditing = $is_auditing_app + $is_auditing_yy;

        /*历史数据*/
		$data = Db::table($this->table_view_app)->where('app_uid',$this->uid)->whereTime('app_visittime', 'week')->count();
		$data_arrive = Db::table($this->table_view_app)->where('appointment_status', 1)->where('app_uid',$this->uid)->whereTime('app_visittime', 'today')->select();
		$data_noarrive = Db::table($this->table_view_app)->where('appointment_status', 0)->where('arrive_status',0)->where('app_uid',$this->uid)->select();
		$data_auditing = Db::table($this->table_view_app)->where('auditing = 0 and vister_uid is not null and app_uid = '.$this->uid)->select();
		
        return toJson(['message'=>'获取首页数据成功','code'=>'200','arrive'=>$is_arrive_leave,'no_arrive'=>$no_arrive,'auditing'=>$is_auditing,'data'=>$data,'data_arrive'=> $data_arrive,'data_noarrive'=>$data_noarrive,'data_auditing'=>$data_auditing]);
		 
	}
	
	/*访客详情*/
	public function index_info(){

        $daybegin = strtotime(date('Y-m-d', time()));
        $dayend = $daybegin+24*60*60;
        $where_nowday = 'app_visittime between "'.$daybegin.'" and "'.$dayend.'"';
        // var_dump($where_nowday);
        $roleid = $this->user->roleid;
        switch ($roleid) {
            case 1:
                $where_arrive = 'appointment_status = 1 and arrive_status in (4,5)';
                $where_noarrive = 'appointment_status = 0 and arrive_status = 0';
                $where_auditing = '';
                break;
            case 2:
            case 8:
            //离开
                $where_arrive = 'companyid = '.$this->user->companyid.' and appointment_status = 1 and arrive_status in (4,5)';
            //未到访
                $where_noarrive = 'companyid = '.$this->user->companyid.' and appointment_status = 0 and arrive_status = 0';
           //审核中
                $where_auditing_1 = 'companyid = '.$this->user->companyid.' and appointment_status = 0 and auditing = 0 and type = 1';
                $where_auditing_2 = 'companyid = '.$this->user->companyid.' and appointment_status = 0 and auditing = 0 and type = 2';
                break;
            case 3:
            //离开
                $where_arrive = 'companyid = '.$this->user->companyid.' and appointment_status = 1 and arrive_status in (4,5) and deptid = '.$this->user->deptid;
            //未到访
                $where_noarrive = 'companyid = '.$this->user->companyid.' and appointment_status = 0 and arrive_status = 0 and deptid = '.$this->user->deptid;
           //审核中
                $where_auditing_1 = 'companyid = '.$this->user->companyid.' and appointment_status = 0 and auditing = 0 and type = 1 and deptid = '.$this->user->deptid;
                $where_auditing_2 = 'companyid = '.$this->user->companyid.' and appointment_status = 0 and auditing = 0 and type = 2 and deptid = '.$this->user->deptid;
                break;
            case 4:
            case 5:
            case 6:
            //离开
                $where_arrive = 'companyid = '.$this->user->companyid.' and appointment_status = 1 and arrive_status in (4,5) and appointment_uid = '.$this->uid;
            //未到访
                $where_noarrive = 'companyid = '.$this->user->companyid.' and appointment_status = 0 and arrive_status = 0 and appointment_uid = '.$this->uid;
           //审核中
                $where_auditing_1 = 'companyid = '.$this->user->companyid.' and appointment_status = 0 and auditing = 0 and type = 1 and appointment_uid = '.$this->uid;
                $where_auditing_2 = 'companyid = '.$this->user->companyid.' and appointment_status = 0 and auditing = 0 and type = 2 and vister_uid = '.$this->uid;
                break;
            default:
                //$where = 'auditing = 0 and type = 2 and vister_uid = '.$this->uid;
                return toJson(['message'=>'无权限请求','code'=>'400','data'=>[]]);
                # code...
                break;

        }

       // //离开
       //  $data_arrive = Db::table('view_new_app_meeting_info')->where('appointment_status', 1)->where('app_uid',$this->uid)->where($where_nowday)->select();
       //  //未到访
       //  $data_noarrive = Db::table('view_new_app_meeting_info')->where('appointment_status','0')->where('arrive_status',0)->where('app_uid',$this->uid)->where($where_nowday)->select();
       //  //审核
       //  $data_auditing = Db::table('view_new_app_meeting_info')->where('auditing = 0 and vister_uid is not null and app_uid ='.$this->uid)->where($where_nowday)->select();

	   //离开
        $data_arrive = Db::table('view_new_app_meeting_info')->where($where_arrive)->where($where_nowday)->select();
        //未到访
        $data_noarrive = Db::table('view_new_app_meeting_info')->where($where_noarrive)->where($where_nowday)->select();
		//审核
        $data_auditing = Db::table('view_new_app_meeting_info')->where('auditing = 0 and vister_uid is not null and app_uid ='.$this->uid)->where($where_nowday)->select();


		       return toJson(['message'=>'获取访客详情成功','code'=>'200','data_arrive'=> $data_arrive,'data_noarrive'=>$data_noarrive,'data_auditing'=>$data_auditing]);
	}

    /**首页历史数据
     * [historydata description]
     * @HtttpRequest                          get|
     * @Author       GNLEON
     * @Param       stime etime 根绝时间范围
     * @DateTime     2020-07-24T09:02:35+0800
     * @LastTime     2020-07-24T09:02:35+0800
     * @return       [type]                   [description]
     */
    public function historydata_bck(){
        date_default_timezone_set('PRC');
        $historydata_Arr =[]; 
        $notarrive_Arr =  ['name'=>'待访问','data'=>[]];
        $isarrive_Arr = ['name'=>'已离开','data'=>[]];
        $isauditing_Arr = ['name'=>'待审核','data'=>[]];
        $s_time = $this->request->param('stime');
        $e_time = $this->request->param('etime');
        $date = [];

        for ($i=0; $i <7 ; $i++) { 
            # code...
            $ytime = strtotime(date("Y-m-d",strtotime("-".$i." day")));//昨天开始时间戳
            $yetime = $ytime+24 * 60 * 60-$i;//昨天结束时间戳
            $notarrive = Db::table($this->table_view_app)
                            ->where('appointment_status = 0 and app_uid = '.$this->uid)
                            ->where('appointment_creatime','between time',[$ytime,$yetime])
                            ->count();

            $isarrive = Db::table($this->table_view_app)
                            ->where('appointment_status = 1 and app_uid = '.$this->uid)
                            ->where('appointment_creatime','between time',[$ytime,$yetime])
                            ->count();

            $isauditing = Db::table($this->table_view_app)
                            ->where('auditing = 0 and app_uid = '.$this->uid)
                            ->where('appointment_creatime','between time',[$ytime,$yetime])
                            ->count();

            /*保存三个数据*/
            $notarrive_Arr['data'][$i] = $notarrive;
            $isarrive_Arr['data'][$i] = $isarrive;
            $isauditing_Arr['data'][$i] = $isauditing;
            /*查 未访问  一离开  待审核*/
            $data = [
                $notarrive_Arr,
                $isarrive_Arr,
                $isauditing_Arr
            ];
            $date[$i] = date("m-d",strtotime("-".$i." day"));
            $fulldate[$i] = date("Y-m-d",strtotime("-".$i." day"));

        }
        return toJson(['message'=>'Success','code'=>200,'data'=>$data,'date'=>$date,'fulldate'=>$fulldate]);
    }
    public function historydata(){
        date_default_timezone_set('PRC');
        $historydata_Arr =[]; 
        $notarrive_Arr =  ['name'=>'待访问','data'=>[]];
        $isarrive_Arr = ['name'=>'已离开','data'=>[]];
        $isauditing_Arr = ['name'=>'待审核','data'=>[]];
        $s_time = $this->request->param('stime');
        $e_time = $this->request->param('etime');
        $date = [];
        $time_arr = [date("Y-m-d",strtotime("-6 day")),date("Y-m-d",time())];//昨天结束时间戳]
        if($s_time && $e_time){
            $time_arr = [$s_time,$e_time];
        }

        $where = ' and view_appointment.status = 0 '; 
        $notarrive_sql = $this->echartssql($this->uid,$time_arr,$where);
        $notarrive_res = Db::query($notarrive_sql);

        $where = ' and view_appointment.status = 2 '; 
        $isarrive_sql = $this->echartssql($this->uid,$time_arr,$where);
        $isarrive_res = Db::query($isarrive_sql);

        $where = ' and view_appointment.status = 0 and view_appointment.auditing ';
        $isauditing_sql = $this->echartssql($this->uid,$time_arr,$where);
        $isauditing_res =  Db::query($isauditing_sql);

        $notarrive_Arr['data'] = array_column($notarrive_res, 'app_count');
        $isarrive_Arr['data'] = array_column($isarrive_res, 'app_count');
        $isauditing_Arr['data'] = array_column($isauditing_res, 'app_count');

        $data = [
            $notarrive_Arr,
            $isarrive_Arr,
            $isauditing_Arr,
        ];
        //获取日期
        $date = array_column($notarrive_res, 'datelist_cur');
        $fulldate = array_column($notarrive_res, 'datelist');

        return toJson(['message'=>'Success','code'=>200,'data'=>$data,'date'=>$date,'fulldate'=>$fulldate]);
    }
    /**
     * 获取会员信息
     * @HtttpRequest                          get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-08-19T09:02:36+0800
     * @LastTime     2020-08-19T09:02:36+0800
     * @return       [type]                   [description]
     */
    protected function vipinfo_BCK($uid =''){
        $userid = $uid!=''?$uid:$this->uid;
        $search[0] = 'userid = '.$userid;
        $search[1] = 'status = 2 and payTime is not null and deletetime is null';
        $search[3] = 'commodity_year = 0 and commodity_month = 1 and commodity_day = 0';
        $search[4] = 'expritime > '.time();
        $where = '';

        foreach ($search as $key => $value) {
            # code...
            if($value){
                $where=$where.$value.' and ';
            }
        }
        $where=substr($where,0,strlen($where)-5);

        //有效使用期
        $month = Db::table($this->table_view_member)->where($where)->sum('amount');
        //过期时间
        $order = 'payTime desc';
        $memberinfo = Db::table($this->table_view_member)->where($where)->order($order)->find();

        if($memberinfo!=NULL){
            $reinfo = [ 
                'member_expritime' => date('Y-m-d',$memberinfo['expritime']),
                'member_ordertitle' => $memberinfo['commodity_title'],
                'member_orderremark' => $memberinfo['commodity_remark'],
                'member_ordercount' => $month,
            ];
        }else{
            $reinfo = [ 
                'member_expritime' => NULL,
                'member_ordertitle' => '免费版',
                'member_orderremark' => '默认套餐',
                'member_ordercount' => NULL,
            ];
        }
        return $reinfo;
    }

    /**
     * 会员信息
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-10-22T15:11:45+0800
     * @LastTime     2020-10-22T15:11:45+0800
     * @param        string                       $uid     [description]
     * @return       [type]                                [description]
     */
    protected function vipinfo($uid =''){
        $userid = $uid!=''?$uid:$this->uid;
        $uinfo = $this->find('user','id = '.$userid);
        $memberinfo = $this->find('view_user_store_member','openid = "'.$uinfo['openid'].'"');
        $companyinfo_member = NULL;
        if($uinfo['companyid']){
            $companyinfo_member =  $this->find('view_company_store_member','companyid = '.$uinfo['companyid']);
        }

        if($memberinfo!=NULL){
            $reinfo = [ 
                'member_expritime' => $memberinfo['vip_date'],
                'member_ordertitle' => $memberinfo['commodity_title'],
                'member_orderremark' => $memberinfo['remark'],
                'member_ordercount' => 0,
                'member_frequency' => $memberinfo['frequency']
            ];
            if($companyinfo_member){
                $reinfo['member_cfrequency'] = $companyinfo_member['frequency'];
            }
        }else{
            $reinfo = [ 
                'member_expritime' => NULL,
                'member_ordertitle' => '免费版',
                'member_orderremark' => '默认套餐',
                'member_ordercount' => NULL,
                 'member_frequency' => 0
            ];
        }
        return $reinfo;




    }
    /**
     * 测试通道密码确认
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     *                 type chpass
     * @DateTime     2020-09-29T09:23:10+0800
     * @LastTime     2020-09-29T09:23:10+0800
     * 
     */
    public function TestUcheck(){
        $type = $this->request->param('type');
        $password = $this->request->param('password')?:'zsicp12308..';
        $new_password = $this->request->param('npassword');
        $true_password = $this->find('sysconfig','name = "Test_Password" ');
        if(!$this->request->param('password')){return toJson(['code'=>400,'message'=>'password fail']);}
        // $salt = md5(Config::get('salt').'zsicp12308..');
        $check = md5(Config::get('salt').$password)==$true_password['val'];

        if(!$check){

            return toJson(['code'=>400,'message'=>'密码错误,请重新验证']);
        }
        
        if($type=='chpass' && $this->user->roleid==1 && $check){
            $res = $this->update('sysconfig', 'name = "Test_Password" ' ,['val'=>md5(Config::get('salt').$password)]);
            return toJson(['code'=>200,'message'=>'password Success CH']); 
        }
        if($check){
            return toJson(['code'=>200,'message'=>'密码正确']);
        }

            return toJson(['code'=>400,'message'=>'密码错误,请重新验证']);

    }
    /**
     * [echartssql description]
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @param [type] $[name] [<description>]
     *                 time  time1 time2 数组 日期格式!
     *                 uid   用户id
     *                 where 额外的where条件(只能是view_appointment的字段) 注意空格
     * @DateTime     2020-11-11T16:34:11+0800
     * @LastTime     2020-11-11T16:34:11+0800
     * @return       [type]                       [description]
     */
    protected function echartssql($uid,$time=[],$where='  '){
        if(!$uid){return toJson(['code'=>400,'message'=>'参数错误']);}
        if($time){

            $sql = "select 
                c2.datelist,
                date_format(c2.datelist, '%m-%d') as datelist_cur,
                IFNULL(uid,".$uid.") as uid,
                IFNULL(app_count,0) as app_count
                from 
                
                (SELECT
                view_appointment.uid,
                Count(view_appointment.uid) AS app_count,
                c1.datelist
                FROM
                view_appointment
                LEFT JOIN calendar AS c1 ON c1.datelist = view_appointment.visittime_new
                WHERE
                view_appointment.uid = ".$uid.$where."
                GROUP BY
                c1.datelist
                ) as companydata RIGHT  JOIN calendar as c2 on c2.datelist = companydata.datelist
                where c2.datelist between '".$time[0]."' and '".$time[1]."'
                GROUP BY c2.datelist";
        }else{
            $sql = "select 
                c2.datelist,
                date_format(c2.datelist, '%m-%d') as datelist_cur,
                IFNULL(uid,".$uid.") as uid,
                IFNULL(app_count,0) as app_count
                from 
                
                (SELECT
                view_appointment.uid,
                Count(view_appointment.uid) AS app_count,
                c1.datelist
                FROM
                view_appointment
                LEFT JOIN calendar AS c1 ON c1.datelist = view_appointment.visittime_new
                WHERE
                view_appointment.uid = ".$uid.$where."
                GROUP BY
                c1.datelist
                ) as companydata RIGHT  JOIN calendar as c2 on c2.datelist = companydata.datelist
                GROUP BY c2.datelist";
        }
        return $sql;

    }
    /**
     * 创建默认会员--请求向的方法--
     * 仅创建个人类型的会员 
     * @remark
     * 如果需要控制器间调用向的将user信息获取方法改为表查出用户userinfo信息后再调用
     */
    protected function make_member($openid,$vip_level=0,$vip_date='2100-12-31'){
        $check_member = $this->find('store_member','openid = "'.$openid.'" and deletetime is null');
        //code
        //$userinfo = $this->find('view_user','openid = "'.$openid.'"');
        //更新
        if($check_member){
            $where = 'id = '.$check_member['id'];
            $udata = [
                'headimg' =>$this->user->headimgurl,
                'nickname'=>$this->user->nickname?:'',
                'phone'=>$this->user->mobile,
                'username'=>$this->user->name,
                'vip_level'=>$vip_level,
                'vip_date'=>$vip_date,
            ];

            $res = $this->update('store_member',$where,$udata);
            return $res;
        }

        //创建
        $data = [
            'commodityid'=>0,
            'openid'=>$this->user->openid,
            'headimg' =>$this->user->headimgurl,
            'nickname'=>$this->user->nickname,
            'phone'=>$this->user->mobile,
            'username'=>$this->user->name,
            'vip_level'=>$vip_level,
            'vip_date'=>$vip_date,
            'status'=>1,
            'frequency'=>0,
            'type'=>1
        ];
        $res = $this->insert('store_member',$data);
        return $res;
    }
    /**
     * 生成分享链接 分享码
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-18T14:28:56+0800
     * @LastTime     2020-11-18T14:28:56+0800
     * 分享码 用户 openid 后6位
     * @return       [type]                       [description]
     */
    public function makeshare_code(){
        //$uid = $this->request->param('uid')?:$this->uid;
        
        $request_link = $this->request->param('link');
        $code = $this->user->openid;
        $code=substr($code,-6);

        $link = 'http://devs.zsicp.com/h5?s='.$code;
        $newlink=$request_link.'&s='.$code;

        $data = [
            'link' => $link,
           
            'code' => $code,
        ];
        if($request_link){$data['newlink'] = $newlink;}
        return toJson(['code'=>200,'message'=>'请求成功','data'=>$data]);
    }

    /**
     * 转短链接
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-19T15:43:35+0800
     * @LastTime     2020-11-19T15:43:35+0800
     * @return       [type]                       [description]
     */
    public function curlink(){
        $links = $this->request->param('url');

        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();

        $result = $wechatOA->shorturl($links);

        return toJson(['code'=>200,'message'=>'请求成功','data'=>$result]);
    }
}
